package it.geosolutions.geoserver.rest.http;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;

public class UsernamePasswordAuthenticator implements GeoServerRestAuthenticator {
    
    private String username;
    
    private String pw;
    
    public UsernamePasswordAuthenticator(String username, String pw) {
        this.username = username;
        this.pw = pw;
    }

    @Override
    public void setAuth(HttpClient client, HttpMethod method) throws URIException {
        Credentials defaultcreds = new UsernamePasswordCredentials(username, pw);
        client.getState().setCredentials(
                new AuthScope(method.getURI().getHost(), method.getURI().getPort()), defaultcreds);
        client.getParams().setAuthenticationPreemptive(true); // GS2 by
                                                              // default
                                                              // always
                                                              // requires
                                                              // authentication
    }
    

}
